<template>
  <div class="userManage wrap-table">
    <el-form
      ref="form"
      :model="searchData"
      label-width="120px"
      class="clearfix flex-div"
    >
      <el-form-item
        label="所在地区"
        class="item-right"
        label-width="80px"
        style="width: 210px"
      >
        <el-select
          v-model="searchData.districtNo"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="item in optionDiq"
            :key="item.DistrictName"
            :label="item.DistrictName"
            :value="item.DistrictNo"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="权限分组"
        class="item-right"
        label-width="120px"
        style="width: 240px"
      >
        <el-select
          v-model="searchData.roleGroup"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in roles"
            :key="item.value + Math.random()"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 310px; margin-left: -60px">
        <el-input
          v-model="searchData.keyWord"
          placeholder="请输入账号/姓名/手机号"
        >
        </el-input>
      </el-form-item>
      <!-- 操作区域 -->
      <div class="flex-r-but">
        <el-button @click="searchHandler" class="pd-bt">查询</el-button>
        <el-button @click="addHandler" type="primary" class="pd-bt"
          >添加</el-button
        >
        <el-button type="success" @click="outPut" class="pd-bt">导出</el-button>
      </div>
    </el-form>
    <!---->
    <template>
      <el-table
        id="outtableFirst"
        :data="tableData"
        border
        empty-text="当前列表为空"
        v-loading="loading"
        element-loading-text="加载中"
        style="width: 100%"
      >
        <el-table-column
          align="center"
          prop="UserCode"
          label="账号"
          min-width="100"
        >
        </el-table-column>
        <el-table-column prop="" label="姓名" align="center" min-width="100">
          <template slot-scope="scope">
            {{ (scope.row.Surname || "") + (scope.row.Name || "") }}
          </template>
        </el-table-column>
        <el-table-column
          prop="RoleGroup"
          :formatter="RoleGroupFormatter"
          label="权限分组"
          align="center"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="Mobile"
          label="手机号"
          align="center"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="CreateTime"
          label="创建时间"
          align="center"
          min-width="100"
        >
        </el-table-column>
        <el-table-column min-width="100" align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="text"
              @click="queryHandler(scope.$index, scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!--分页-->
    <div class="block mg-20-auto">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pageCount"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加初筛对象的对话框 -->
    <el-dialog
      :title="dialogTitle"
      :close-on-click-modal="false"
      :append-to-body="true"
      top="0"
      :visible.sync="dialogFormVisible"
    >
      <div>
        <el-form
          :model="form"
          label-position="left"
          :rules="rules"
          ref="ruleForm"
        >
          <el-form-item
            label="账号"
            :label-width="formLabelWidth"
            prop="UserCode"
          >
            <el-input v-model="form.UserCode" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="姓" :label-width="formLabelWidth" prop="Surname">
            <el-input v-model="form.Surname" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="名" :label-width="formLabelWidth">
            <el-input v-model="form.Name" auto-complete="off"></el-input>
          </el-form-item>

          <el-form-item
            label="权限分组"
            :label-width="formLabelWidth"
            prop="RoleGroup"
          >
            <el-select v-model="RoleGroup" placeholder="请选择权限分组">
              <el-option
                v-for="role in roles"
                :label="role.label"
                :value="role.value"
                :key="role.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="手机号"
            :label-width="formLabelWidth"
            prop="Mobile"
          >
            <el-input
              v-model="form.Mobile"
              type="tel"
              auto-complete="off"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="密码"
            :label-width="formLabelWidth"
            prop="Password"
          >
            <el-input
              v-model="form.Password"
              type="password"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="社区专属"
            :label-width="formLabelWidth"
            v-if="RoleGroup > 2 && RoleGroup < 12"
          >
            <el-select v-model="form.IsCommunityOnly" @change="changeOnly">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            class="is-required"
            label="所在地区"
            :label-width="formLabelWidth"
            v-if="RoleGroup > 2 && form.IsCommunityOnly == '1'"
          >
            <el-select
              v-model="form.DistrictNo"
              placeholder="请选择"
              @change="changeDis('1')"
            >
              <el-option
                v-for="item in optionDiq"
                :key="item.DistrictName"
                :label="item.DistrictName"
                :value="item.DistrictNo"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            class="is-required"
            label="所在社区"
            :label-width="formLabelWidth"
            v-if="RoleGroup > 2 && form.IsCommunityOnly == '1'"
          >
            <el-select
              v-model="CtyIds"
              placeholder="请选择"
              @change="Commutysp"
              clearable
            >
              <el-option
                v-for="item in options1"
                :key="item.SYS_ID"
                :label="item.CName"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用" :label-width="formLabelWidth">
            <el-select v-model="form.IsStopUse">
              <el-option label="是" value="0"></el-option>
              <el-option label="否" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveHandler">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import FileSaver from "file-saver"; //导出
import XLSX from "xlsx";
export default {
  data() {
    var validateMobile = (rule, value, callback) => {
      let regex = new RegExp(
        /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
      );

      if (!value || value == "") {
        callback();
      } else if (value !== "" && value.length !== 11) {
        callback(new Error("请输入正确的手机号位数"));
      } else {
        if (regex.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的手机号"));
        }
      }
    };
    var validatePassword = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入密码"));
      } else if (value !== "" && value.length < 6) {
        callback(new Error("密码长度不小于6位"));
      } else {
        callback();
      }
    };
    return {
      currentDate: new Date(),
      searchData: {
        keyWord: "",
        districtNo: "",
        roleGroup: "",
      },
      RoleGroup: "",
      sysId: "",
      dialogTitle: "添加账号",
      dialogFormVisible: false,
      formLabelWidth: "100px",
      optionDiq: [],
      options1: [],
      optionDiq: [],
      form: {
        Surname: "",
        CreateTime: "",
        Name: "",
        UserCode: "",
        Password: "",
        Mobile: "",
        IsPasswordChanged: "0",
        DistrictNo: "",
        RoleGroup: "",
        IsCommunityOnly: "0",
        IsStopUse: "0",
      },
      maxHeight: "",
      rules: {
        UserCode: [
          {
            required: true,
            message: "请输入账号，支持字母和数字",
            trigger: "blur",
          },
        ],
        Password: [
          { required: true, validator: validatePassword, trigger: "blur" },
        ],
        Mobile: [{ validator: validateMobile, trigger: "blur" }],
        RoleGroup: [
          {
            required: true,
            message: "请选择分组权限",
            trigger: "blur",
          },
        ],
      },
      tableData: [],
      pageCount: 1,
      changeData: false,
      total: null,
      loading: false,
      CtyIds: "",
      pageSize: 10,
      labelPassword: "",
      options1: [],
      roles: [
        { label: "系统管理员", value: 1 },
        { label: "项目经理", value: 2 },
        { label: "健康访谈人员", value: 3 },
        { label: "APP职员", value: 4 },
        { label: "营养师", value: 5 },
        { label: "健教老师", value: 6 },
        { label: "社区HCP干预组", value: 7 },
        { label: "社区HCP对照组", value: 8 },
        { label: "哺乳顾问", value: 9 },
        { label: "数据采集", value: 10 },
        { label: "儿科医生", value: 11 },
        { label: "内部评估员", value: 12 },
        { label: "外部评估员", value: 13 },
      ],
    };
  },
  beforeMount: function () {
    let that = this;
    let appHeight = $(window).height();
    let autoheight = appHeight - 200 + "px";
    that.maxHeight = autoheight;
  },
  watch: {
    "form.Password"(value) {
      if (this.labelPassword != this.form.Password) {
        this.form.IsPasswordChanged = "1";
      }
    },
    "form.UserCode"(value) {
      this.form.UserCode = value.replace(/[\W]/g, "");
    },
    RoleGroup(value) {
      this.form.RoleGroup = value;
      if (value == "7" || value == "8") {
        this.form.IsCommunityOnly = "1";
      }
    },
  },
  methods: {
    GetCommunityDistrict: function () {
      //获取社区行政区
      let that = this;
      that
        .service({
          url: "/Dic/GetCommunityDistrict",
          method: "get",
          params: {},
        })
        .then((response) => {
          that.optionDiq = response.dtData;
        })
        .catch((data) => {});
    },
    outPut: function () {
      //导出
      /* generate workbook object from table */
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#outtableFirst")
      );
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
        width: "300",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "账号列表.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    RoleGroupFormatter(row, column, cellValue, index) {
      return this.roles[cellValue - 1].label;
    },
    changeOnly(val) {
      if (val == "0") {
        this.form.DistrictNo = "";
        this.CtyIds = "";
        this.form.CommunityId = "";
      }
    },
    GetCommunityDistrict: function () {
      //获取社区行政区
      let that = this;
      that
        .service({
          url: "/Dic/GetCommunityDistrict",
          method: "get",
          params: {},
        })
        .then((response) => {
          that.optionDiq = response.dtData;
        })
        .catch((data) => {});
    },
    async getComselectList() {
      //获取社区信息
      let that = this;
      await that
        .service({
          url: "dic/GetCommunity",
          method: "get",
          params: {
            cName: "",
            cGroup: "",
            DistrictNo: that.form.DistrictNo || "",
            pageCount: 0,
            pageSize: 100,
          },
        })
        .then((resp) => {
          let obj = {
            CGroup: "",
            Code: "",
            SYS_ID: "",
            CName: "全部",
          };
          that.options1 = resp.dtData;
        })
        .catch((data) => {});
    },
    Commutysp: function (val) {
      this.CtyIds = val.CName;
      val.SYS_ID !== undefined
        ? (this.form.CommunityId = val.SYS_ID)
        : (this.form.CommunityId = "");
    },
    changeDis: function (val) {
      //选择地区
      this.CtyIds = "";
      this.form.CommunityId = "";
      this.getComselectList();
    },
    MobileFilter(row, column, cellValue, index) {
      return cellValue.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    },
    handleSizeChange(val) {
      //条数改变
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      //页数改变
      this.pageCount = val;
      this.getList();
    },
    getList() {
      let that = this;
      this.loading = true;
      that
        .service({
          url: "sys/GetAdmin",
          method: "get",
          params: {
            sysId: that.sysId,
            pageCount: that.pageCount - 1,
            pageSize: that.pageSize,
            ...that.searchData,
          },
        })
        .then((response) => {
          that.tableData = response.dtData;
          that.total = parseInt(response.dtData[0].TotalCount);
          that.loading = false;
        })
        .catch((data) => {
          that.loading = false;
        });
    },
    searchHandler() {
      this.pageCount = 1; // 分页索引
      this.total = null;
      this.pageSize = 10;
      this.getList();
    },
    // 查看操作
    async queryHandler(index, row) {
      this.CtyIds = "";
      !row.IsStopUse ? (row.IsStopUse = "0") : ""; //账户默认启用
      this.dialogFormVisible = true;
      if (row) {
        this.dialogTitle = "查看账号";
        this.$nextTick(async () => {
          this.$refs.ruleForm.resetFields();
          this.form = JSON.parse(JSON.stringify(row));
          this.RoleGroup = this.form.RoleGroup;
          this.form.IsPasswordChanged = "0";
          this.labelPassword = this.form.Password;
          await this.getComselectList();
          this.CtyIds = (
            this.options1.find((val, index) => {
              return val.SYS_ID == this.form.CommunityId;
            }) || ""
          ).CName;
        });
      }
    },
    addHandler() {
      this.dialogTitle = "添加账号";
      this.RoleGroup = "";
      this.form = JSON.parse(
        JSON.stringify({
          Surname: "",
          CreateTime: "",
          Name: "",
          RoleGroup: "",
          UserCode: "",
          Password: "",
          Mobile: "",
          IsCommunityOnly: "0",
          IsPasswordChanged: "0",
          IsStopUse: "0",
        })
      );
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.CtyIds = "";
        this.options1 = [];
      });
    },
    saveHandler() {
      let _this = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 校验权限分组
          if (this.form.RoleGroup == null || this.form.RoleGroup == "") {
            this.$message({
              message: "请选择权限分组",
              type: "error",
            });
            return;
          }
          if (
            _this.form.IsCommunityOnly == "1" &&
            !this.form.DistrictNo &&
            !this.form.CommunityId
          ) {
            this.$message({
              message: "请填入所在地区、所在社区 ",
              type: "error",
            });
            return;
          }
          if (this.form.IsPasswordChanged == "1") {
            var crypto = require("crypto");
            var md5 = crypto.createHash("md5");
            md5.update(this.form.Password);
            var str = md5.digest("hex");
            this.form.Password = str.toUpperCase(); //32位大写
          }
          _this
            .service({
              url: "Sys/SaveAdmin",
              method: "post",
              data: {
                ..._this.form,
              },
            })
            .then((resp) => {
              _this.getList();
              _this.dialogFormVisible = false;
            })
            .catch((data) => {
              _this.getList();
              _this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  mounted() {
    this.getList();
    this.GetCommunityDistrict();
  },
};
</script>
<style>
</style>
